package vtt.android.dapanhc;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;

import vtt.android.dapanhc.database.AnswerDAO;
import vtt.android.dapanhc.dialogs.DialogManager;
import vtt.android.dapanhc.dialogs.DialogManager.IDialogListener;
import vtt.android.dapanhc.entities.Answer;
import vtt.android.dapanhc.utils.VttAlarmManager;
import vtt.android.library.utils.VttUtils;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MainActivity extends BaseActivity implements MainDrawerFragment.NavigationDrawerCallbacks, IDialogListener {

	public static final String KEY_IS_START_ALARM = "KEY_IS_START_ALARM";
	private static final String DL_INTERNET_ALERT = "DL_INTERNET_ALERT";
	private static final String DL_SCORE_ALERT = "DL_SCORE_ALERT";

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private MainDrawerFragment mDrawerFragment;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */
	private CharSequence mTitle;

	private static ProgressBar progressBar;

	private static AnswerDAO answerDAO;
	

	private static DialogManager dialogManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		answerDAO = AnswerDAO.getInstance(this);
		answerDAO.open();
		
		dialogManager = new DialogManager(this);
		dialogManager.addDialogListener(this);
		
		mDrawerFragment = (MainDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
		mTitle = getTitle();
		
		progressBar = (ProgressBar) findViewById(R.id.progressbar_loading);
		
		// Set up the drawer.
		mDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
		
		if(!VttUtils.checkNetworkConnection(this)){
			dialogManager.showAlertDialog(DL_INTERNET_ALERT, getString(R.string.msg_title_notice), getString(R.string.msg_network_error), false);
		}
		
		SharedPreferences sharedPreferences = getSharedPreferences("DapAnHC", MODE_PRIVATE);
		boolean isStartAlarm = sharedPreferences.getBoolean(KEY_IS_START_ALARM, false);
		if(!isStartAlarm){
			// set repeat alarm everyday for showing notification
			// startAlarm(this);
			VttAlarmManager.startAlarmEveryday(mContext, 1, MyBroadcastReceiver.class);
			sharedPreferences.edit().putBoolean(KEY_IS_START_ALARM, true).commit();
		}
	}

	@Override
	public void onNavigationDrawerItemSelected(String date) {
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getSupportFragmentManager();
		fragmentManager.beginTransaction().replace(R.id.container, MainContentFragment.newInstance(date))
				.commit();
	}

	public void onSectionAttached(String date) {
		mTitle = date;
	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main, menu);
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		answerDAO.close();
	}
	
	/**
	 * 
	 * @return format day:   yyyyMMdd
	 */
	public static String getCurrentDayString(){
		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		return sf.format(now);
	}
	
	public static String getCurrentDayString2(){
		Date now = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
		return sf.format(now);
	}
	
	public static String revertYYYYMMDD(String ddMMyyy){
		String[] dateArr = ddMMyyy.split("/");
		return dateArr[2] + dateArr[1] + dateArr[0];
	}

	/**
	 * A placeholder fragment containing a webview.
	 */
	public static class MainContentFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_CHALLENGE_DATE = "challenge_date";
		
		private String selectedDate = "";
		
		public MainContentFragment() {
		}
		
		/**
		 * Returns a new instance of this fragment for the given section number.
		 */
		public static MainContentFragment newInstance(String date) {
			MainContentFragment fragment = new MainContentFragment();
			Bundle args = new Bundle();
			args.putString(ARG_CHALLENGE_DATE, date);
			fragment.setArguments(args);
			return fragment;
		}
	
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_page, container, false);
			selectedDate = getArguments().getString(ARG_CHALLENGE_DATE);
			initWebview(rootView);
			
			return rootView;
		}
	
		@Override
		public void onAttach(Activity activity) {
			super.onAttach(activity);
			((MainActivity) activity).onSectionAttached(getArguments().getString(ARG_CHALLENGE_DATE));
		}
		
		
		/*
		 * init webview
		 */
		private WebView initWebview(View rootView) {
			
			// Look up the AdView as a resource and load a request.
		    AdView adView = (AdView) rootView.findViewById(R.id.adView);
		    AdRequest adRequest = new AdRequest.Builder()
		    		.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
		    		.addTestDevice("AD3EA773211B100433F351BBFFAE240C")
		    		.build();

		    adView.loadAd(adRequest);
			
			WebView webView = (WebView) rootView.findViewById(R.id.webView1);
			WebSettings webSettings = webView.getSettings();
			webSettings.setJavaScriptEnabled(true);
			webSettings.setBuiltInZoomControls(false);
	
			webView.addJavascriptInterface(new AndroidBridge(), "Android");
			webView.setWebViewClient(new WebClient());
			webView.setWebChromeClient(new WebChromeClient() {
				public void onProgressChanged(WebView view, int progress) {
					// update the progressBar
					progressBar.setProgress(progress);
					if(progress >= 100){
						progressBar.setProgress(100);
						progressBar.setVisibility(View.GONE);
					}
				}
			});
			
			//webView.requestFocus(View.FOCUS_DOWN);
			webView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
			webView.loadUrl("file:///android_asset/html/index.html");
			return webView;
		}
		
		/*
		 * Android bridge
		 */
		class AndroidBridge {
			
			MediaPlayer player;
			
			public AndroidBridge() {
				// prepare source at the first time
				player = new MediaPlayer();
				player.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					player.setDataSource("http://www.hellochao.vn/play_sound.php?sid=e4da5b7fbbce234527779b0674a318Ms&type=11");
					player.prepareAsync();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			public void playAudio(String url){
				log.d("VTT>>> playAudio " + url);
				
				if(!VttUtils.checkNetworkConnection(getActivity())){
					dialogManager.showAlertDialog(DL_INTERNET_ALERT, getString(R.string.msg_title_notice), getString(R.string.msg_network_error), false);
					return;
				}
				
				if(player != null){
					player.release();
					player = null;
				}
				
				player = new MediaPlayer();
				player.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					player.setDataSource(url);
					player.setOnErrorListener(new OnErrorListener() {
						@Override
						public boolean onError(MediaPlayer mp, int what, int extra) {
							log.d("VTT>>>player onError what " + what + " extra " + extra);
							EasyTracker.getInstance();
							EasyTracker.getTracker().sendException("Can not play sound : what " + what + "; extra " + extra + "; device info : " + VttUtils.getDeviceInfo(), false);
							return false;
						}
					});
					player.setOnPreparedListener(new OnPreparedListener() {
						@Override
						public void onPrepared(MediaPlayer mp) {
							mp.start();
						}
					});
					player.prepareAsync();
				} catch (Exception e) {
					Toast.makeText(getActivity(), 
							R.string.msg_err_play_audio,
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}
			
			public void saveAnswer(String sid, String suggestion, String en, String vn, String soundUrl){
				//log.d("VTT>>> AndroidBridge saveAnswer " + String.format("('%s', '%s', '%s', '%s', '%s', '%s');", sid,suggestion, en, vn, soundUrl, getCurrentDayString()));
				answerDAO.saveAnswer(new Answer(sid, suggestion, en, vn, soundUrl, getCurrentDayString()));
			}
			
			public boolean isNewDate(){
				return answerDAO.checkNewDate(getCurrentDayString());
			}
			
			public String loadOldAnswer(){
				try {
					String yyyyMMdd = revertYYYYMMDD(selectedDate);
					JSONArray answerArray = answerDAO.loadAnswerByDate(yyyyMMdd);
					return answerArray.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				return null;
			}
			
			// GA
			public void sendEvent(String action){
				EasyTracker.getInstance();
				EasyTracker.getTracker().sendEvent("UserClick", action, "", null);
			}
			
			// show log
			public void log(String tag, String msg){
				log.d("VTT>>> " + tag + " : " + msg);
			}
			
			// show dialog
			public void showDialog(String title, String message){
				dialogManager.showAlertDialog(DL_SCORE_ALERT, title, message, false);
			}
		}
		
		class WebClient extends WebViewClient {
	
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				progressBar.setVisibility(View.VISIBLE);
				progressBar.setProgress(0);
				super.onPageStarted(view, url, favicon);
			}
	
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}
	
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return super.shouldOverrideUrlLoading(view, url);
			}
		}
		
		public static void saveUrl(final String urlString, final String filename)
		        throws MalformedURLException, IOException {
			
		    BufferedInputStream in = null;
		    FileOutputStream fout = null;
		    try {
		        URL url = new URL(urlString);
				URLConnection urlConnection = url.openConnection();
				urlConnection.setRequestProperty("User-Agent", "NING/1.0");
				InputStream inputStream = urlConnection.getInputStream();
		        
				in = new BufferedInputStream(inputStream);
		        fout = new FileOutputStream(filename);
	
		        final byte data[] = new byte[1024];
		        int count;
		        while ((count = in.read(data, 0, 1024)) != -1) {
		            fout.write(data, 0, count);
		        }
		        log.d("VTT>>> filename " + filename);
		    }catch (Exception ex){
		    	ex.printStackTrace();
		    }finally {
		        if (in != null) {
		            in.close();
		        }
		        if (fout != null) {
		            fout.close();
		        }
		    }
		}
	}

	@Override
	public void onOkClick(String dialogName) {
		log.d("VTT>>> onOkClick " + dialogName);
		if (DL_INTERNET_ALERT.equals(dialogName)) {
			
		}
	}

	@Override
	public void onCancelClick(String dialogName) {
		log.d("VTT>>> onCancelClick " + dialogName);
		if (DL_INTERNET_ALERT.equals(dialogName)) {

		}
	}
}
